﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebCore_MVC.Services;
using WebCore_MVC.Models;
using Microsoft.EntityFrameworkCore;

namespace WebCore_MVC.Controllers
{
    public class EditController : Controller
    {

        private readonly ServiceContext ServiceContext;
        public EditController(ServiceContext serviceContext)
        {
            ServiceContext = serviceContext;
        }

     
        public async Task <IActionResult> Index()
        {
            ViewData["Items"] =await GetItems();
            return View();
        }

       
        [HttpPost()]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(User model)
        {
            if (ModelState.IsValid)
            {
                ServiceContext.DbContext.Set<User>().Add(model);

                var i = await ServiceContext.DbContext.SaveChangesAsync();

                if (i > 0)
                {
                    return RedirectToAction("Index");
                }

                ModelState.AddModelError(string.Empty, string.Empty);
            }

            return View(model);
        }

        public async Task<IEnumerable<User>> GetItems()
        {
            var items= await ServiceContext.DbContext.Set<User>().ToListAsync();

            var result = new List<User>();
            foreach (var item in items)
            {
                result.Add(item);   
            }
            return result;
        }
    }
}
